<?php

function post($url, $post_data)
{
    //初始化
    $curl = curl_init();
    //设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $url);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 0);
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    //设置post方式提交
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post_data));
    //执行命令
    $data = curl_exec($curl);
    //关闭URL请求
    curl_close($curl);
    //显示获得的数据
    return $data;
}

function start($file, $uploadUrl, $sleep = 0, $chunkSize = '1048576')
{
    if (!file_exists($file)) return false;
    $flag = true;
    $handle = fopen($file, "rb");
    if ($handle === false) return false;
    $filename = basename($file);
    $filesize = filesize($file);
    $md5 = md5_file($file);
    $total = ceil($filesize / $chunkSize);
    echo "文件md5：{$md5}\n";
    echo "文件大小：{$filesize}，需分为{$total}片段\n";
    $i = 1;
    $start_time = time();
    while (!feof($handle)) {
        $data = fread($handle, $chunkSize);
        $result = post($uploadUrl, [
            'index' => $i,
            'total' => $total,
            'filename' => $filename,
            'filesize' => $filesize,
            'md5' => $md5,
            'data' => $data,
        ]);

        $json = json_decode($result, true);
        if (!$json['status']) {
            $flag = false;
            break;
        }

        echo "片段：{$i}上传成功！\n";
        echo $result . "\n";
        if ($sleep > 0) {
            usleep($sleep);
        }
        $i++;
    }
    fclose($handle);
    if (!$flag) {
        echo "上传失败\n";
        return false;
    }
    $stop_time = time();
    $spent_time = $stop_time - $start_time;
    echo "上传完成耗时：{$spent_time}秒\n";
    return true;
}

$file = '1.mp4';

start($file, 'http://localhost/1.php', 1000, 1024 * 800);

//echo md5_file("D:\\phpstudy_pro\\WWW\\1.mp4")."\n";